# -*- coding:utf-8 -*-
"""
炽链财经
http://chilian.io/
"""
import requests
import json
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def post_html_text(url, data):
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"}
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_tt(url, data):
    text = post_html_text(url, json.dumps(data))
    text = eval(text)
    datas = text['data']
    dates = [date['date'][:10].replace('年', '-').replace('月', '-') for date in datas]
    mm = [date['seqence'] for date in datas]
    return (dates, mm)


def count_process_tt():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    maxDate = 0
    minDate = 0
    l = []
    a = 1
    while a < 100:
        data = {
            "base": {"apn": "wifi",
                     "appId": "001",
                     "brand": "huawei",
                     "carrier": "china mobile",
                     "channels": "001",
                     "city": "合肥",
                     "clientVer": "1.0",
                     "deviceId": "1233eedds2112",
                     "deviceType": "P6",
                     "lalong": "12.332112",
                     "platform": "IOS",
                     "platformVer": "8",
                     "resolution": "960*640",
                     "uid": "12332112",
                     "valat": "22.332112",
                     "ver": "1.0.1"
                     },
            "param": {
                "action": "1",
                "channelId": "222145508ed84606b444299ddea18159",
                "maxDate": maxDate,
                "minDate": minDate,
            }

        }
        url = 'https://rolaiapp.aioff.com/newNews/queryNewsListlimit'
        print('----炽链财经头条获取第{}页----'.format(a))
        a += 1
        dates = get_dates_tt(url, data)
        if not dates:
            continue
        maxDate = max(dates[1])
        if maxDate in l:
            break
        l.append(maxDate)
        minDate = min(dates[1])
        for date in dates[0]:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '炽链财经'
    t1 = count_process_tt()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
